<script lang="ts" setup>
import type { PropType } from "vue";
import { getSpeInfoApi, getCouponSpecDetail } from "@/api/activity";
import { deepClone } from "@/utils";
import StockPrizeFormItem from "./components/StockPrizeFormItem.vue";

const props = defineProps({
  modelValue: {
    type: Object as PropType<any>,
  },
  show: {
    type: Boolean,
    default: false,
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits([ "update:modelValue", "update:show", "submit" ]);

const formRef = ref();

watch(
  () => props.show,
  (val) => {
    nextTick(() => {
      if (val) {
        if (!props.modelValue.prizeSpecifications) {
          return;
        }

        props.modelValue.prizeSpecifications.forEach(async (item: any) => {
          if (item.type === 'systemCoupon') {
            let specDetail = await _getCouponSpecDetail(item.goodsSpeId)
            item.couponTotalNum = specDetail.couponTotalNum
            item.couponReceiveNum = specDetail.couponReceiveNum
          } else if (item.goodsSpeId) {
            let specDetail = await getSpecDetail(item.goodsSpeId);
            item.specStock = specDetail.beforeStock;
          }
          item.originalStock = item.stock || 0;
          item.originalStockTotal = item.totalStock || 0;
          if (item.stype === null || item.stype === undefined) item.stype = 1;
        });

        if (props.modelValue.defaultSpec) {
          props.modelValue.defaultSpec.originalStock =
            props.modelValue.defaultSpec.stock || 0;
          props.modelValue.defaultSpec.originalStockTotal =
            props.modelValue.defaultSpec.totalStock || 0;
        }
      }
    });
  },
  { immediate: true, deep: true }
);

// 优惠券类型商品
const isCoupon = computed(() => props.modelValue.prizeType === 4)

const validateSpecStockNum = (rule: any, value: any, callback: any) => {
  let attr = rule.field.split(".");
  let index = attr[1];
  let spec = props.modelValue.prizeSpecifications[index];
  console.log("validate spec => ", spec)
  // 优惠券类型商品的库存增减规则
  if (isCoupon.value) {
    // 可配置库存
    const remainStock = spec.couponTotalNum - spec.couponReceiveNum
    if (spec.stype === 1 && spec.num > (remainStock - spec.stock)) {
      callback(new Error(`新增的库存不能大于 (可配置库存 - 剩余库存)`));
      return
    }
        
    if (spec.stype === 2 && spec.num > spec.stock) {
      callback(new Error(`减少的库存不能大于剩余库存`));
      return
    }

    callback()
    return
  }

  // 加库存不能超过规格总库存
  if (spec.stype == 1 && Number(value) > Number(spec.specStock || 0)) {
    callback(new Error("新增库存不能超过规格剩余库存"));
  } else if (spec.stype == 2 && Number(spec.stock - value) < 0) {
    callback(new Error("库存不能小于0"));
  }
  // 礼品包库存校验
  if (props.modelValue.prizeType === 3 && spec.onlineStatus == 1) {
    if (props.modelValue.packNum === -1) {
      let diffrenet = Number(`${spec.stype == 1 ? "+" : "-"}${value || 0}`);
      let newStock = spec.originalStock + diffrenet;
      if (newStock < bagStock.value) {
        callback(new Error("规格库存不能小于礼品包库存"));
      }
    }
  }
  callback();
};

const bagStock = computed(() => {
  let diffrenet = Number(
    `${props.modelValue.defaultSpec.stype == 1 ? "+" : "-"}${
      props.modelValue.defaultSpec.num || 0
    }`
  );
  return props.modelValue.defaultSpec.originalStock + diffrenet;
});

// 加减库存
const changeSType: any = (index: number) => {
  formRef.value.validateField(`prizeSpecifications.${index}.num`);
};

// 规格商品库存
const getSpecDetail = async (id: string | number) => {
  const rs = await getSpeInfoApi({ id });
  if (rs.code == 200) {
    return rs.payload;
  }
  return null;
};

// 优惠券批次
const _getCouponSpecDetail = async (id: string | number) => {
  const rs = await getCouponSpecDetail({ id })
  if (rs.code == 200) {
    return rs.payload;
  }
  return null;
}

// 校验规格库存
const onCheckStock = () => {
  props.modelValue.prizeSpecifications.forEach((item: any, index: number) => {
    changeSType(index);
  });
};

const onConfirm = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (props.modelValue.prizeType === 3) {
        if (props.modelValue.packNum === 1) {
          let total = props.modelValue.prizeSpecifications.reduce(
            (total: number, item: any) => {
              let diffrenet = Number(
                `${item.stype == 1 ? "+" : "-"}${item.num || 0}`
              );
              let newStock = item.stock + diffrenet;
              return total + newStock;
            },
            0
          );
          if (total < bagStock.value) {
            ElNotification.error({
              message: "规格库存之和不能小于礼品包库存",
            });
            return;
          }
        }
      }
      emits("update:modelValue", props.modelValue);
      emits("submit", props.modelValue);
    }
  });
};

const onClose = () => {
  emits("update:show", false);
};
</script>
<template>
  <Dialog
    :model-value="show"
    :title="modelValue.type == 'status' ? '商品上架' : '调整库存'"
    :loading="loading"
    close-on-click-modal
    :width="900"
    @confirm="onConfirm"
    @close="onClose"
  >
    <h3 style="margin-bottom: 10px">
      商品名称：{{ modelValue.name }}
    </h3>
    <el-form
      ref="formRef"
      :model="modelValue"
      label-width="auto"
    >
      <template
        v-if="modelValue.prizeType === 3 && modelValue.type !== 'bagSpecStatus'"
      >
        <StockPrizeFormItem
          v-model="modelValue.defaultSpec"
          prefix="defaultSpec."
          label="礼品包库存"
          @check="onCheckStock"
        />
      </template>
      <el-table
        :data="modelValue.prizeSpecifications"
        style="width: 100%"
      >
        <el-table-column
          align="center"
          prop="name"
          label="规格名称"
          min-width="150"
        />
        <el-table-column
          v-if="modelValue.type !== 'stock'"
          align="center"
          label="状态"
          min-width="100"
        >
          <template #default="scope">
            <el-switch
              v-model="
                modelValue.prizeSpecifications[scope.$index].onlineStatus
              "
              inline-prompt
              active-text="上架"
              inactive-text="下架"
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="剩余库存/总库存"
          min-width="150"
        >
          <template #default="scope">
            <span>
              {{ scope.row.originalStock }}
              /
              {{ scope.row.originalStockTotal }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          v-if="isCoupon"
          align="center"
          prop="address"
          label="可配置库存"
          min-width="150"
        >
          <template #default="scope">
            {{ scope.row.couponTotalNum - scope.row.couponReceiveNum }}
          </template>
        </el-table-column>

        <el-table-column
          v-else
          align="center"
          prop="address"
          label="商家剩余库存"
          min-width="150"
        >
          <template #default="scope">
            {{
              scope.row.specStock === Infinity ? "" : scope.row.specStock
            }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="设置库存"
          min-width="280"
        >
          <template #default="scope">
            <div
              class="flex-container"
              style="padding: 10px 0 20px"
            >
              <el-radio-group
                v-model="modelValue.prizeSpecifications[scope.$index].stype"
                @change="changeSType(scope.$index)"
              >
                <el-radio-button :label="1">
                  加
                </el-radio-button>
                <el-radio-button :label="2">
                  减
                </el-radio-button>
              </el-radio-group>
              <el-form-item
                label-width="10px"
                :prop="`prizeSpecifications.${scope.$index}.num`"
                :rules="[{ validator: validateSpecStockNum, trigger: 'blur' }]"
              >
                <EasyNumberInput
                  v-model="modelValue.prizeSpecifications[scope.$index].num"
                  :min="1"
                  :max="99999999"
                  unit="件"
                  :precision="0"
                  style="width: 150px"
                />
              </el-form-item>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </Dialog>
</template>
<style lang="scss" scoped>
.flex-container {
  display: flex;
  align-items: center;
  .el-form-item {
    margin-bottom: 0;
    :deep(.el-form-item__error) {
      white-space: nowrap;
    }
  }
}
</style>
